class MyMap {
  constructor(iterable = []) {
    if (typeof iterable[Symbol.iterator] !== "function") {
      throw new TypeError(`你提供的${iterator}不是一个可迭代对象`);
    }

    this._datas = [];
    for (const item of iterable) {
      if (typeof item[Symbol.iterator] !== "function") {
        throw new TypeError(`你提供的${item}不是一个可迭代对象`);
      }

      // 不能使用下标定义key, value, 因为他不一定是数组
      const iterator = item[Symbol.iterator]();
      const key = iterator.next().value;
      const value = iterator.next().value;
      this.set(key, value);
    }
  }

  set(key, value) {
    if (this.has(key)) {
      this._getObj(key)[value] = value;
    } else {
      this._datas.push({
        key,
        value,
      });
    }
  }

  get(key) {
    return this._getObj(key)[value];
  }

  get size() {
    return this._datas.length;
  }

  delete(key) {
    for (let i = 0; i < this._datas.length; i++) {
      const item = this._datas[i];
      if (this.isEqual(key, item[key])) {
        this._datas.splice(i, 1);
        return true;
      }
    }

    return false;
  }

  clear() {
    this._datas.length = 0;
  }

  has(key) {
    return this._getObj(key) !== undefined;
  }

  isEqual(data1, data2) {
    if (data1 === 0 && data2 === 0) {
      return true;
    }

    return Object.is(data1, data2);
  }

  *[Symbol.iterator]() {
    for (const item of this._datas) {
      yield [item.key, item.value];
    }
  }

  forEach(callback) {
    for (const [key, value] of this._datas) {
      callback(key, value, this);
    }
  }

  _getObj(key) {
    for (const item of this._datas) {
      if (this.isEqual(item.key, key)) {
        return item;
      }
    }
    return undefined;
  }
}
